﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
using System.Web.Mvc;
using CollegeWebsite.Models;

namespace CollegeWebsite.Controllers
{
    public class CourseController : Controller
    {
        public CourseController()
        {

        }

        readonly CollegeDataContext _dataContext = new CollegeDataContext();
        public static Admission ThisAdmission { get; set; }
        public static Student ThisStudent { get; set; }
        public static Course ThisCourse { get; set; }
        //
        // GET: /Couse/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult CourseInfo(FormCollection formCollection)
        {
            int dep, fal, crs;


            List<Course> listCourse = _dataContext.Courses.Select(c => c).ToList();
            if (Request.HttpMethod == "POST")
            {
                dep = Convert.ToInt32(formCollection.Get("Department"));
                fal = Convert.ToInt32(formCollection.Get("Faculty"));
                crs = Convert.ToInt32(formCollection.Get("Course"));
            }
            else
            {
                dep = Convert.ToInt32(Request.QueryString.Get("Department"));
                fal = Convert.ToInt32(Request.QueryString.Get("Faculty"));
                crs = Convert.ToInt32(Request.QueryString.Get("Course"));
            }

            if (fal > 0)
            {
                listCourse =
                    _dataContext.Courses.Select(c => c).Where(c => (c.Department.FacultyID == fal)).ToList();
            }
            if (dep > 0)
            {
                listCourse =
                    _dataContext.Courses.Select(c => c).Where(c => (c.DepartmentID == dep)).ToList();
            }

            if (crs > 0)
            {
                listCourse =
                    _dataContext.Courses.Select(c => c).Where(c => (c.CourseID == crs)).ToList();
            }

            return View(listCourse);
        }

        public ActionResult Apply(int id)
        {
            Common com = new Common();
            Session["captcha"] = com.CreateCaptcha("5");
            if (id > 0)
            {
                ApplyCourse(id);
                var student = new Student
                                      {
                                          Gender = true
                                      };


               
                return View(student);
            }
          
                ViewData["WarningInfo"] = "There are no content";
                return View("Error");
       
        }



        private void ApplyCourse(int id)
        {
            try
            {
                ThisCourse =
               _dataContext.Courses.Select(c => c).Where(c => (c.CourseID == id)).Single();
                ViewData["Course"] = ThisCourse;
                


            }
            catch (Exception ex)
            {

                var a = ex;
            }

        }

        [HttpPost]
        public ActionResult Apply(int id, Student student, FormCollection form)
        {
            Common com = new Common();
            string serverhash = form.Get("undefinedHash");
            string clientcode = form.Get("entercaptcha");
            string clientHast = com.CreateCaptcha(clientcode);
            if(serverhash != clientHast)
            {
                ViewData["ErrorInfo"] = "Captcha not match";
                return View("Error");
            }
    
            IFormatProvider culture = new CultureInfo("en-US", true);

            {
                int applyCourseId = id;
                ApplyCourse(id);
            }
            try
            {
                _dataContext.Students.InsertOnSubmit(student);

                _dataContext.SubmitChanges();


                var admission = new Admission
                                    {
                                        CourseID = id,
                                        StudentID = student.StudentID,
                                        Status = false
                                    };
                _dataContext.Admissions.InsertOnSubmit(admission);
                _dataContext.SubmitChanges();

                ThisStudent = student;
                ThisAdmission = admission;


                /*****************************************/

                var infoCount = form.GetValues("University");
                if (infoCount != null && infoCount.Count() > 0)
                {
                    for (int i = 0; i < infoCount.Count(); i++)
                    {


                        var spi = new StudentPreviousInfomation();
                        spi.University = form.GetValues("University").ElementAt(i);
                        spi.EnrollmentNo = Convert.ToInt32(form.GetValues("EnrollmentNo").ElementAt(i));
                        spi.Center = form.GetValues("Center").ElementAt(i);
                        spi.Stream = form.GetValues("Stream").ElementAt(i);
                        spi.Field = form.GetValues("Field").ElementAt(i);
                        spi.MarksSecured = form.GetValues("MarksSecured").ElementAt(i);
                        var ood = form.GetValues("OutOfDate").ElementAt(i);
                        spi.OutOfDate = DateTime.ParseExact(ood, "MM/dd/yyyy", culture, DateTimeStyles.NoCurrentDateDefault);
                        spi.ClassObitained = form.GetValues("ClassObitained").ElementAt(i);
                        spi.StudentID = student.StudentID;

                        _dataContext.StudentPreviousInfomations.InsertOnSubmit(spi);


                    }
                    _dataContext.SubmitChanges();

                }

                /***********************************************/




                return RedirectToAction("ApplyComplete");

            }
            catch (Exception ex)
            {
                return View();
            }


        }



        public ActionResult ApplyComplete()
        {
            var Strcode = new string('0', 12);
            var code = Strcode.ToCharArray();
            var prefix = "DFC";


            var postfix = "S" + ThisAdmission.StudentID + "C" + ThisAdmission.CourseID;
            var postfixchar = postfix.ToCharArray();
            for (int i = postfixchar.Length; i > 0; i--)
            {
                code[code.Length - i] = postfixchar[postfixchar.Length - i];
            }
            string s = new string(code);
            ViewData["AdmissionCode"] = prefix + s;

            ViewData["Course"] = ThisCourse;
            return View(ThisStudent);
        }


        [HttpPost]
        public ActionResult CheckPIN(string PIN)
        {
            int count = _dataContext.Students.Select(s => s).Where(s => s.PIN == PIN).Count();
            bool hadPIN = (count > 0) ? true : false;
            return Json(hadPIN);
        }


    }
}